package com.ns.dcjh.base;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings;
import android.view.View;
import android.view.inputmethod.InputMethodManager;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.alibaba.fastjson.JSONObject;
import com.ns.dcjh.MyApplication;
import com.ns.dcjh.R;
import com.ns.dcjh.bean.MessageEvent;
import com.ns.dcjh.utils.StatusBarUtils;
import com.orhanobut.logger.Logger;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.ButterKnife;
import constant.UiType;
import listener.UpdateDownloadListener;
import model.UiConfig;
import model.UpdateConfig;
import update.UpdateAppUtils;

public abstract class BaseActivity extends AppCompatActivity {
    protected MyApplication mApp;
    protected BaseActivity mContext = this;
    protected Handler mHandler = new Handler();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mApp = MyApplication.getInstance();
        mApp.addActivity(mContext);
        initStatusBar();
        initTransition();
        setContentView(getLayoutId());
        ButterKnife.bind(this);
        initData();
        initView();
        initListener();
        dataRequest();
    }

    @Override
    protected void onResume() {
        super.onResume();

        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }

        mHandler.removeCallbacksAndMessages(null);

        mApp.quitActivity(mContext);

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MessageEvent messageEvent) {

    }

    //设置页面过度方式
    protected void initTransition() {

    }

    protected void initStatusBar() {
        StatusBarUtils.setStatusBarColor(mContext, Color.parseColor("#343434"), false);
    }

    //获取layout
    protected abstract int getLayoutId();


    //数据初始化
    protected abstract void initData();

    //view初始化
    protected abstract void initView();

    //监听初始化
    protected abstract void initListener();

    //数据请求
    protected abstract void dataRequest();

    //检测用户是否开启开发者模式，不保留活动
    protected void checkAlwaysFinish() {
        int setting = Settings.Global.getInt(
                getContentResolver(),
                Settings.Global.ALWAYS_FINISH_ACTIVITIES,
                0
        );
        if (setting != 1)       return;

        AlertDialog mDialog = new AlertDialog.Builder(mContext)
                .setTitle(R.string.txt_dialog_title)
                .setMessage(R.string.msg_user_open_always_finish_activities)
                .setNegativeButton(R.string.txt_cancel, (dialog, which) -> dialog.dismiss())
                .setPositiveButton(R.string.txt_setting, (dialog, which) -> {
                    Intent intent = new Intent(Settings.ACTION_APPLICATION_DEVELOPMENT_SETTINGS);
                    startActivity(intent);
                })
                .create();
        mDialog.show();
    }

    //APP更新
    protected void startUpgrade(JSONObject data) {
        Logger.d("Start Upgrade");
        UpdateAppUtils.init(this);

        UpdateConfig config = new UpdateConfig();
        config.setForce(data.getBoolean("force"));
        config.setCheckWifi(true);
        config.setNeedCheckMd5(false);
        config.setShowNotification(true);
        config.setNotifyImgRes(R.mipmap.ic_logo_1);

        UiConfig uiConfig = new UiConfig();
        uiConfig.setUiType(UiType.SIMPLE);

        UpdateAppUtils.getInstance()
                .apkUrl(data.getString("url"))
                .updateTitle("发现新版本")
                .updateContent(data.getString("description"))
                .updateConfig(config)
                .uiConfig(uiConfig)
                .setUpdateDownloadListener(new UpdateDownloadListener() {
                    @Override
                    public void onStart() {
                        Logger.d("开始更新");
                    }

                    @SuppressLint("DefaultLocale")
                    @Override
                    public void onDownload(int i) {
                        Logger.d(String.format("下载进度 %d", i));
                    }

                    @Override
                    public void onFinish() {
                        Logger.d("更新完成");
                    }

                    @Override
                    public void onError(Throwable throwable) {
                        Logger.d("更新失败");
                    }
                })
                .update();
    }
}
